// 客户管理功能实现

// 从本地存储加载客户数据
function loadCustomers() {
    const customers = localStorage.getItem('customers');
    return customers ? JSON.parse(customers) : [];
}

// 保存客户数据到本地存储
function saveCustomers(customers) {
    localStorage.setItem('customers', JSON.stringify(customers));
}

// 初始化客户列表
function initCustomerList() {
    const customerListBody = document.getElementById('customer-list-body');
    const customers = loadCustomers();

    // 清空客户列表
    customerListBody.innerHTML = '';

    // 添加客户到列表
    customers.forEach(customer => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${customer.name}</td>
            <td>
                <button class="btn delete-btn" data-name="${customer.name}">删除</button>
            </td>
        `;
        customerListBody.appendChild(row);
    });

    // 绑定删除按钮事件
    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const customerName = this.getAttribute('data-name');
            deleteCustomer(customerName);
        });
    });
}

// 添加新客户
function addCustomer(name) {
    if (!name || name.trim() === '') {
        alert('请输入客户名称');
        return;
    }

    const customers = loadCustomers();

    // 检查客户是否已存在
    if (customers.some(customer => customer.name === name)) {
        alert('该客户已存在');
        return;
    }

    // 添加新客户
    customers.push({ name: name });
    saveCustomers(customers);

    // 更新客户列表
    initCustomerList();

    // 清空输入框
    document.getElementById('new-customer-name').value = '';

    alert('客户添加成功');
}

// 删除客户（包括级联删除相关销售记录）
function deleteCustomer(name) {
    if (confirm(`确定要删除客户 '${name}' 及其相关销售记录吗？`)) {
        // 删除客户
        let customers = loadCustomers();
        customers = customers.filter(customer => customer.name !== name);
        saveCustomers(customers);

        // 级联删除相关销售记录
        let salesRecords = loadSalesRecords();
        salesRecords = salesRecords.filter(record => record.customerName !== name);
        saveSalesRecords(salesRecords);

        initCustomerList();
        alert('客户及其相关销售记录删除成功');
    }
}

// 从本地存储加载销售记录
function loadSalesRecords() {
    const salesRecordsJson = localStorage.getItem('salesRecords') || '[]';
    return JSON.parse(salesRecordsJson);
}

// 保存销售记录到本地存储
function saveSalesRecords(records) {
    localStorage.setItem('salesRecords', JSON.stringify(records));
}

// 初始化添加客户按钮事件
function initAddCustomerButton() {
    document.getElementById('confirm-add-customer').addEventListener('click', function() {
        const customerName = document.getElementById('new-customer-name').value;
        addCustomer(customerName);
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initCustomerList();
    initAddCustomerButton();
});